package com.yanghui.dtracing.core;

import com.yanghui.dtracing.core.classLoader.AgentClassLoader;
import com.yanghui.dtracing.core.log.LogManager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class PluginResourceResolver {

    public List<URL> getPluginDefineResource(){
    	return getDefineResource(AgentClassLoader.getDefault(), "agent.def");
    }
    
    public List<URL> getLogDefineResource(){
    	return getDefineResource(LogManager.getLogClassLoader(), "log.def");
    }

    public List<URL> getReportDefineResource(ClassLoader classLoader){
        return getDefineResource(classLoader, "reporter.def");
    }
    
    private List<URL> getDefineResource(ClassLoader classLoader,String defineName){
    	List<URL> result = new ArrayList<URL>();
        try {
            Enumeration<URL> enumeration = classLoader.getResources(defineName);
            while(enumeration.hasMoreElements()){
                URL url = enumeration.nextElement();
                result.add(url);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public List<String> getDefines(URL url) {
        List<String> result = new ArrayList<>();
        InputStream in = null;
        InputStreamReader inreader = null;
        BufferedReader bufferedReader = null;
        try{
            in = url.openStream();
            inreader = new InputStreamReader(in);
            bufferedReader = new BufferedReader(inreader);
            String line = null;
            while((line = bufferedReader.readLine()) != null){
            	if(line.startsWith("#")) {
            		continue;
            	}
                result.add(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(null != in){
                    in.close();
                }
                if(null != inreader){
                    inreader.close();
                }
                if(null != bufferedReader){
                    bufferedReader.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }
}
